<?php
class FaceService {
	const SUCCESS = 'success';
	const ERROR = 'error';
	//0审核中 1不通过 
	//存储头像的路径
	private $_savefacePath = "/static/attached/face/";
	private $_status = array (0 => "等待审核", 1 => "通过", - 1 => "不通过" );
	
	public function __construct() {
	
	}
	
	/**
	 * 新增加头像队列
	 * @param int $uid
	 * @param String $face
	 * @param String $username
	 */
	public function add($uid, $face, $username) {
		if ($this->checkUser ( $uid )) {
			$this->addUser ( $face, $uid, $username );
		} else {
			$this->saveUser ( $face, $uid, $username );
		}
	}
	
	private function saveUser($face, $uid, $username) {
		return FaceModel::instance ()->saveFaceByUid ( array ('face' => $face, 'username' => $username, 'status' => 0 ), $uid );
	}
	
	private function addUser($face, $uid, $username) {
		return FaceModel::instance ()->addFaceList ( array ('face' => $face, 'uid' => $uid, 'username' => $username, 'status' => 0 ) );
	}
	
	/**
	 * 检查申请队列是否已经存在
	 * @param int $uid
	 * @return true 不存在 false 存在
	 */
	private function checkUser($uid) {
		$user = FaceModel::instance ()->getFaceByUid ( $uid );
		//删除了原有的图片
		unlink ( ROOT . $user ['face'] );
		return empty ( $user ) ? true : false;
	}
	
	/**
	 * 验证头像
	 * @param int $id
	 * @param String $type
	 */
	public function validFace($id, $type) {
		$face = FaceModel::instance ()->getFaceById ( $id );
		
		if ($type == 'pass') {
			//删除申请
			FaceModel::instance ()->saveFaceByid ( array ('status' => 1 ), $id );
			//删除申请记录 确保下次不被覆盖掉
			$this->delFaceById ( $id );
			return $face;
		} else {
			FaceModel::instance ()->saveFaceByid ( array ('status' => - 1 ), $id );
			return self::ERROR;
		}
	
	}
	
	public function delFaceById($id) {
		return FaceModel::instance ()->delFaceById ( $id );
	}
	/**
	 * 获取所有提交的头像审核
	 */
	public function getVaildFaceList() {
		return FaceModel::instance ()->getFaceList ();
	}
	
	/**
	 * 上传头像
	 */
	public function upload($uid) {
		
		$image = new Image ();
		$face = $image->upload ( $_FILES ['face'], "face", false );
		//自动缩小
		$face=$face['message'];
		$sface = $image->reduceImage ( $face, 360, 360, "face" );
		
		//删除原图
		@unlink ( getcwd () . $face );
		
		//增加队列
		$this->add ( $uid, $sface, "" );
		
		return $sface;
	}

}